#include "mt6816.h"
#include "stdio.h"

MT6816_SPI_Signal_Typedef mt6816_spi;

void MT6816_SPI_Signal_Init(void) 
{
	mt6816_spi.sample_data = 0;
	mt6816_spi.angle = 0;
	SPI1->CR1 |= SPI_CR1_SPE;
}

void MT6816_SPI_Get_AngleData(void) {
	uint16_t data_t[2];
	uint16_t data_r[2];
	uint8_t h_count;
	data_t[0] = (0x80 | 0x03) << 8;
	data_t[1] = (0x80 | 0x04) << 8;
//	for (uint8_t i = 0; i < 3; i++) 
//	{
		//读取SPI数据
		MT6816_SPI_CS_L();
		SPI1->DR = data_t[0];
		while (!(SPI1->SR & SPI_SR_RXNE));
		data_r[0] = SPI1->DR;
		//HAL_SPI_TransmitReceive(&MT6816_SPI_Get_HSPI, (uint8_t*) &data_t[0], (uint8_t*) &data_r[0], 1, 200);
		MT6816_SPI_CS_H();
		MT6816_SPI_CS_L();
		//HAL_SPI_TransmitReceive(&MT6816_SPI_Get_HSPI, (uint8_t*) &data_t[1], (uint8_t*) &data_r[1], 1, 200);
		SPI1->DR = data_t[1];
		while (!(SPI1->SR & SPI_SR_RXNE));
		data_r[1] = SPI1->DR;
		MT6816_SPI_CS_H();
		mt6816_spi.sample_data = ((data_r[0] & 0x00FF) << 8) | (data_r[1] & 0x00FF);
		//奇偶校验
		h_count = __builtin_popcount(mt6816_spi.sample_data);
//		for (uint8_t j = 0; j < 16; j++) 
//		{
//			if (mt6816_spi.sample_data & (0x0001 << j))
//				h_count++;
//		}
		if (h_count & 0x01) 
		{
			mt6816_spi.pc_flag = false;
		} 
		else 
		{
			mt6816_spi.pc_flag = true;
			//break;
		}
	//}
	if (mt6816_spi.pc_flag) 
	{
		mt6816_spi.angle = mt6816_spi.sample_data >> 2;
		mt6816_spi.no_mag_flag = (bool) (mt6816_spi.sample_data & (0x0001 << 1));
	}
}

MT6816_Typedef mt6816;

float MT6816_Get_AngleData() 
{
	MT6816_SPI_Get_AngleData();
	mt6816.angle_data = mt6816_spi.angle;
	return mt6816.angle_data;
}
